#include "opedb.h"
#include <QMessageBox>
#include <QDebug>

OpeDB::OpeDB(QObject *parent)
    : QObject{parent}
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
}

OpeDB &OpeDB::getInstance()
{
    static OpeDB instance;

    return instance;
}

void OpeDB::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("F:\\WorkSpace\\Qt\\NetDisk\\TcpServer\\netdisk.db");

    if(m_db.open())
    {
        QSqlQuery query;
        query.exec("select * from userInfo");

        while(query.next())
        {
            QString data = QString("%1, %2, %3").arg(query.value(0).toString()).arg(query.value(1).toString()).arg(query.value(2).toString());
            qDebug() << data;
        }

    }
    else
    {
        QMessageBox::critical(NULL, "打开数据库", "打开数据库失败");
    }
}

bool OpeDB::handleRegist(const char *name, const char *pwd)
{
    if(name == NULL || pwd ==NULL)
    {
        return false;
    }
    qDebug() << name;
    QString data = QString("insert into userInfo(name, pwd) values(\'%1\', \'%2\')").arg(name).arg(pwd);
    QSqlQuery query;

    return query.exec(data);
}

bool OpeDB::handleLogin(const char *name, const char *pwd)
{
    if(name == NULL || pwd ==NULL)
    {
        return false;
    }
    QString data = QString("select * from userInfo where name is \'%1\' and pwd is \'%2\' and online = 0").arg(name).arg(pwd);
    QSqlQuery query;

    query.exec(data);

    if(query.next())
    {
        QString data = QString("update userInfo set online = 1 where name is \'%1\' and pwd is \'%2\'").arg(name).arg(pwd);
        QSqlQuery query;

        query.exec(data);
        return true;
    }
    else
    {
        return false;
    }
}

bool OpeDB::handleCancel(const char *name, const char *pwd)
{
    if(name == NULL || pwd ==NULL)
    {
        return false;
    }
    QString data = QString("delete * from userInfo where name is %1 and pwd is %2").arg(name).arg(pwd);
    QSqlQuery query;

    return query.exec(data);
}

void OpeDB::handleOffline(const char *name)
{
    if(name == NULL)
    {
        return;
    }

    QString data = QString("update userInfo set online = 0 where name is \'%1\'").arg(name);
    QSqlQuery query;
    query.exec(data);
}

OpeDB::~OpeDB()
{
    m_db.close();
}
